package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件输入/输出流
 * @author galen
 */
public class FileInput {
    public static void main(String[] args) {
        // 文件输入流
        String path = "D:/Java/www/Demo/test.txt";
        File f = new File(path);
        FileInputStream fils = null;
        try {
            fils = new FileInputStream(f);
            byte[] bytes = new byte[1024];
            int n = 0;
            System.out.println("==============");
            while ((n = fils.read(bytes)) != -1) {
                String s = new String(bytes, 0, n);
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fils.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 文件输出流
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File srcFile = new File(path);
            fis = new FileInputStream(srcFile);

            // 创建目标文件对象，该文件不存在
            String targetPath = "D:/Java/www/Demo/target.txt";
            File targetFile = new File(targetPath);
            fos = new FileOutputStream(targetFile);

            byte[] bytes = new byte[1024];
            int i = fis.read(bytes);
            while (i != -1) {
                // 向文件中写入内容
                fos.write(bytes, 0, i);
                i = fis.read(bytes);
            }
            System.out.println("写入结束！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close(); // 关闭FileInputStream对象
                fos.close(); // 关闭FileOutputStream对象
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
